﻿using PurchaseOrderChangeListBP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.Base;
using UFIDA.U9.Base.Doc;
using UFIDA.U9.CBO.MFG.PMM;
using UFIDA.U9.InvDoc.LendTrans;
using UFIDA.U9.ISV.PO;
using UFIDA.U9.PM.DTOs;
using UFIDA.U9.PM.PO;
using UFIDA.U9.PM.POChange;
using UFIDA.U9.SM.SO;
using UFSoft.UBF.Business;
using UFSoft.UBF.Transactions;
using UFSoft.UBF.Util.Context;
using UFSoft.UBF.Util.Log;

namespace ufida.u9.ait.openapi
{
    internal class POModifyBase
    {
        /// <summary>
        /// 引用集团示例方法,稍作修改
        /// 现支持
        /// 新增行
        /// 修改行,修改数量/单价/金额
        /// 关闭行
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        private static PurchaseOrder CreatePOModify(POAITDTOData dto)
        {
            UFIDA.U9.Base.Organization.Organization org = UFIDA.U9.Base.Context.LoginOrg;
            //检查该单号是否存在
            PurchaseOrder po = PurchaseOrder.Finder.Find("DocNo='" + dto.DocNo + "'");
            if (po == null)
            {
                throw new Exception($"采购订单[{dto.DocNo}]不存在");
            }

            PlatformContext context = PlatformContext.Current;
            //查询出采购订单
            UFIDA.U9.ISV.PO.Proxy.QueryPODTOByDocNOSRVProxy queryProxy = new UFIDA.U9.ISV.PO.Proxy.QueryPODTOByDocNOSRVProxy();
            queryProxy.PODocNOList = new List<string>();
            queryProxy.PODocNOList.Add(po.DocNo);
            List<UFIDA.U9.PM.DTOs.OBAPurchaseOrderDTOData> queryPOList = queryProxy.Do();
            OBAPurchaseOrderDTOData queryPO = queryPOList[0];

            //对比新行与旧行
            List<ObjUtils.OperItem> operItems = ObjUtils.CompareList(dto.POLines, queryPO.POLines, "DocLineNo");

            bool isModify = false;
            List<POLineKeyDTO> closeList = new List<POLineKeyDTO>();
            foreach (var item in operItems)
            {
                if (item.oper == ObjUtils.OperEnum.add)
                {
                    isModify = true;
                    //新增行
                    POLineAITDTOData newline = (POLineAITDTOData)item.item1;
                    OBAPOLineDTOData addline = new OBAPOLineDTOData();

                    addline.DocLineNo = newline.DocLineNo;
                    addline.ItemInfo = new UFIDA.U9.CBO.SCM.Item.ItemInfoData()
                    {
                        ItemCode = newline.ItemInfo.ItemCode,
                    };
                    addline.PurQtyTU = newline.PurQtyTU;
                    addline.FinallyPriceTC = newline.TotalMnyTC / newline.PurQtyTU;
                    addline.TotalMnyTC = newline.TotalMnyTC;
                    //queryPOLine.TotalMnyAC = firstModifyLineData.TotalMnyTC;
                    //queryPOLine.TotalMnyFC = firstModifyLineData.TotalMnyTC;
                    //queryPOLine.PriceSource = UFIDA.U9.CBO.SCM.Enums.PriceSourceEnum.Custom.Value; //值1
                    addline.TaxSchedule = queryPO.TaxSchedule;
                    addline.APIActionType = POAPIActionEnum.APIAdd.Value;
                    addline.IsPriceModify = true;
                    addline.SysState = UFSoft.UBF.PL.Engine.ObjectState.Inserted;//行新增

                    queryPO.POLines.Add(addline);
                }
                else if (item.oper == ObjUtils.OperEnum.update)
                {
                    
                    POLineAITDTOData newline = (POLineAITDTOData)item.item1;
                    OBAPOLineDTOData oldline = (OBAPOLineDTOData)item.item2;
                    //修改行
                    if(oldline.PurQtyTU != newline.PurQtyTU
                        || oldline.TotalMnyTC != newline.TotalMnyTC)
                    {
                        isModify = true;

                        oldline.PurQtyTU = newline.PurQtyTU;//采购数量
                        oldline.PurQtyPU = newline.PurQtyTU;
                        oldline.PurQtyCU = newline.PurQtyTU;
                        oldline.SupplierConfirmQtyTU = newline.PurQtyTU;//确认数量
                        oldline.SupplierConfirmQtyPU = newline.PurQtyTU;
                        oldline.SupplierConfirmQtyCU = newline.PurQtyTU;
                        oldline.FinallyPriceTC = newline.TotalMnyTC / newline.PurQtyTU;//最终价
                        oldline.TotalMnyTC = newline.TotalMnyTC;//总金额

                        //queryPOLine.TotalMnyAC = firstModifyLineData.TotalMnyTC;
                        //queryPOLine.TotalMnyFC = firstModifyLineData.TotalMnyTC;
                        //queryPOLine.PriceSource = UFIDA.U9.CBO.SCM.Enums.PriceSourceEnum.Custom.Value; //值1
                        //oldline.APIActionType = POAPIActionEnum.APIModifyPrice.Value;  //值1
                        oldline.APIActionType = POAPIActionEnum.APIModifyPrice.Value;
                        oldline.IsPriceModify = true;
                        oldline.SysState = UFSoft.UBF.PL.Engine.ObjectState.Updated;//行修改
                    }
                    else
                    {
                        queryPO.POLines.Remove(oldline);
                    }
                    
                }
                else if (item.oper == ObjUtils.OperEnum.delete)
                {
                    OBAPOLineDTOData oldline = (OBAPOLineDTOData)item.item2;
                    //删除行
                    queryPO.POLines.Remove(oldline);
                    POLine poline = POLine.Finder.FindByID(oldline.ID);
                    if (poline == null) throw new Exception("依据行ID查询POLine失败!");
                    if (poline.Status == PODOCStatusEnum.Approved)
                    {
                        closeList.Add(new POLineKeyDTO()
                        {
                            LineKeyDTO = new UFIDA.U9.Base.DTOs.IDCodeNameDTO()
                            {
                                ID = oldline.ID,
                            }
                        });
                    }
                }
            }

            if (isModify)
            {
                long poModifyID = 0;
                try
                {
                    //如果创建变更单，需要传这个值 值为2
                    queryPO.ModifyOperType = (int)ModifyOperTypeEnumData.CreatePOModify;

                    //PO变更
                    UFIDA.U9.ISV.PO.Proxy.ModifyPOSRVProxy proxy = new UFIDA.U9.ISV.PO.Proxy.ModifyPOSRVProxy();
                    proxy.POList = queryPOList;
                    proxy.Do(org.ID);
                }
                catch (Exception ex)
                {
                    if (!String.IsNullOrEmpty(ex.Message) && ex.Message.Length == 16)
                    {
                        //标准产品创建成功的
                        long.TryParse(ex.Message.ToString(), out poModifyID);
                    }
                    else
                    {
                        throw new Exception("创建采购订单变更单报错：" + ex.Message);
                    }
                }
                if (poModifyID > 0)
                {
                    POModify poModify = POModify.Finder.FindByID(poModifyID);
                    if (poModify == null)
                        throw new Exception($"依据ID查找采购变更单失败!");
                    //变更单提交
                    CommitDoc(poModify);
                    //变更单审核
                    ApproveDoc(poModify);
                }
            }
            if (closeList.Count>0)
            {
                //关闭订单行
                ClosePOLineSRV closePOLineSRV = new ClosePOLineSRV();
                closePOLineSRV.POLineKeyDTOs = closeList;
                closePOLineSRV.Do();
            }
            
            return po;
        }

        public static PurchaseOrder CreateDoc(POAITDTOData dto, PurchaseOrder po)
        {
            CreatePOModify(dto);
            return po;
        }

        public static POModify RevocateDoc(POModify doc)
        {
            doc = doc.Key.GetEntity();
            if (doc.Status != POChangeListStatusEnum.Approving)
                throw new Exception($"单号：[{doc.DocNo}]状态不为提交，不能收回！");

            using (ISession session = Session.Open())
            {
                doc.Status = POChangeListStatusEnum.Opened;
                session.Commit();
            }
            return doc;
        }

        public static POModify ApproveDoc(POModify doc)
        {
            doc = doc.Key.GetEntity();
            if (doc.Status != POChangeListStatusEnum.Approving)
                throw new Exception($"单号：[{doc.DocNo}]状态不为提交，不能审核！");

            List<POModifyDTO> list = new List<POModifyDTO>();
            list.Add(new POModifyDTO
            {
                IDKey = doc.Key,
                SysVersion = doc.SysVersion,
            });

            POModifyApproveBP bp = new POModifyApproveBP();
            bp.POModifyDTOs = list;
            bp.Do();

            //POModify _POModify = POModify.Finder.FindByID(poModifyID);//版本号更新
            //_POModify.ApprovedBy = Context.LoginUser;
            //_POModify.ApprovedOn = PlatformContext.Current.OperationDate;
            //if (_POModify.IsNeedCheckApproveFlow && _POModify.DocumentType.ConfirmType.Value == ConfirmTypeEnum.ApproveFlow.Value)
            //{
            //    // throw new Exception("采购订单变更单的确认方式为审批流程，不能手工审核");
            //    throw new Exception(POModifySubmitBPRes.Res2);
            //}
            //else if (!_POModify.IsNeedCheckApproveFlow)
            //{
            //    _POModify.IsNeedCheckApproveFlow = true;
            //}
            //_POModify.Status = POChangeListStatusEnum.Approved;

            //POModifyDTO POdto = new POModifyDTO();
            //POdto.POModify = _POModify;

            //POModifyUpdatePOBP _POModifyUpdatePOBP = new POModifyUpdatePOBP();
            //_POModifyUpdatePOBP.POModifyDTOs = POdto;
            //_POModifyUpdatePOBP.POModifyDTOs.IDKey = _POModify.Key;//必须要有
            //_POModifyUpdatePOBP.IsSimulation = false;
            //_POModifyUpdatePOBP.Do();

            return doc;
        }

        public static POModify CommitDoc(POModify doc)
        {
            doc=doc.Key.GetEntity();
            //变更单提交
            using (ISession session = Session.Open())
            {
                doc.Status = POChangeListStatusEnum.Approving;
                session.Commit();

            }

            return doc;
        }
        
    }
}
